package com.net.spring_security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import com.net.dao.ResourceDao;
import com.net.model.Resource;
import com.net.model.Role;

public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource  {
	private ResourceDao resourceDao;
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();;
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public MyInvocationSecurityMetadataSource() {
		
	}

	private void loadResource() {
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		Collection<ConfigAttribute> atts = null;
		//System.out.println(resourceDao);
		List<Resource> urlResources = (List<Resource>)resourceDao.listAll();
		for(Resource resource : urlResources){
			atts = new ArrayList<ConfigAttribute>();
			Set<Role> roles = (Set<Role>) resource.getRoles();
			for(Role role : roles){
				atts.add(new SecurityConfig(role.getName()));
			}
			resourceMap.put(resource.getValue(), atts);
		}
	}

	// According to a URL, Find out permission configuration of this URL.
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		// guess object is a URL.
		loadResource();
		String url = ((FilterInvocation)object).getRequestUrl();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (urlMatcher.pathMatchesUrl(url, resURL)) {
				return resourceMap.get(resURL);
			}
		}
		return null;
	}
	
	public Collection<ConfigAttribute> getAllConfigAttributes() {

		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}


	public static Map<String, Collection<ConfigAttribute>> getResourceMap() {
		return resourceMap;
	}

	public static void setResourceMap(
			Map<String, Collection<ConfigAttribute>> resourceMap) {
		MyInvocationSecurityMetadataSource.resourceMap = resourceMap;
	}

	public ResourceDao getResourceDao() {
		return resourceDao;
	}
	@javax.annotation.Resource(name="resourceDao")
	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	public UrlMatcher getUrlMatcher() {
		return urlMatcher;
	}

	public void setUrlMatcher(UrlMatcher urlMatcher) {
		this.urlMatcher = urlMatcher;
	}

}
